import java.util.*;

public class Producer implements Runnable
{
	static final int MAXQUEUE = 5;
	private List<String> messages = new ArrayList<String>();

	public void run()
	{
		while ( true ) {
			putMessage();
			try {
				Thread.sleep( 1000 ); 
			} catch ( InterruptedException e ) { }
		}
	}

	private synchronized void putMessage()
	{
		while ( messages.size() >= MAXQUEUE ) {
			try {
				wait();
			} catch( InterruptedException e ) { }
		}

		messages.add( new java.util.Date().toString() );
		System.out.println("Producer> Add message: "
			+ messages.get(messages.size()-1) );
		notifyAll();
	}

	// called by Consumer
	public synchronized String getMessage()
	{
		while ( messages.size() == 0 ) {
			try {
				notifyAll();
				wait();
			} catch( InterruptedException e ) { }
		}
		String message = messages.remove(0);
		notifyAll();
		return message;
	}
}

